package com.ekuaitu.kuaitustaff.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ekuaitu.kuaitustaff.R;
import com.ekuaitu.kuaitustaff.adapter.GridViewAddImgesAdpter;
import com.ekuaitu.kuaitustaff.adapter.GridViewAdpter;
import com.ekuaitu.kuaitustaff.api.ApiService;
import com.ekuaitu.kuaitustaff.api.ApiStore;
import com.ekuaitu.kuaitustaff.api.UrlConstant;
import com.ekuaitu.kuaitustaff.application.MyApplication;
import com.ekuaitu.kuaitustaff.base.BaseActivity;
import com.ekuaitu.kuaitustaff.bean.ReturnCarCommentBean;
import com.ekuaitu.kuaitustaff.bean.UploadImageBaidu;
import com.ekuaitu.kuaitustaff.utils.AppManager;
import com.ekuaitu.kuaitustaff.utils.CheckRegexUtils;
import com.ekuaitu.kuaitustaff.utils.Constants;
import com.ekuaitu.kuaitustaff.utils.Logger;
import com.ekuaitu.kuaitustaff.utils.SDCardUtils;
import com.ekuaitu.kuaitustaff.utils.SPKey;
import com.ekuaitu.kuaitustaff.utils.SPUtils;
import com.ekuaitu.kuaitustaff.utils.ToastUtils;
import com.ekuaitu.kuaitustaff.utils.UploadPicUtil;
import com.ekuaitu.kuaitustaff.widget.NoScrollGridView;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class AddCommentActivity extends BaseActivity {

    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.iv_search)
    ImageView ivSearch;
    @BindView(R.id.edt_search)
    EditText edtSearch;
    @BindView(R.id.tv_cancel)
    TextView tvCancel;
    @BindView(R.id.linear_cancel)
    LinearLayout linearCancel;
    @BindView(R.id.comment_tv_licensetag)
    TextView commentTvLicensetag;
    @BindView(R.id.comment_gv0)
    NoScrollGridView commentGv0;
    @BindView(R.id.comment_tv_tip)
    TextView commentTvTip;
    @BindView(R.id.comment_gv1)
    NoScrollGridView commentGv1;
    @BindView(R.id.tv_sure)
    TextView tvSure;
    @BindView(R.id.linearLayout)
    LinearLayout linearLayout;
    private Context mContext = this;
    private GridViewAddImgesAdpter gridViewAddImgesAdpter;
    private ArrayList<String> datas;
    private String orderId = "000000";
    private int maxImages;
    private GridViewAdpter gridViewAdpter;
    private String imgs, key;
    private ReturnCarCommentBean getCarCommentBean;
    private File fileDir;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_add_comment;
    }

    @Override
    protected void initView() {
        edtSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(s) && linearCancel.getVisibility() == View.GONE) {
                    linearCancel.setVisibility(View.VISIBLE);
                } else if (TextUtils.isEmpty(s)) {
                    linearCancel.setVisibility(View.GONE);
                }
            }
        });
        edtSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    if (TextUtils.isEmpty(edtSearch.getText().toString())) {
                        ToastUtils.makeText(mContext, "请输入要查询的车牌号", ToastUtils.LENGTH_SHORT).show();
                    } else {
                        if (CheckRegexUtils.isCarNum(edtSearch.getText().toString())) {
                            String licenseTag = edtSearch.getText().toString();
                            getComment(licenseTag);
                        } else {
                            dismissLoadingDialog();
                            ToastUtils.makeText(mContext, "请输入正确的车牌号", ToastUtils.LENGTH_SHORT).show();
                        }
                    }
                }
                return false;
            }
        });

    }

    private void getComment(String licenseTag) {
        showLoadingDialog();
        new ApiStore().getRetrofit(UrlConstant.Request.BASE_URL_NEW, "", "").create(ApiService.class).getCommentByLicense("epimetheus/v1/cars/" + URLEncoder.encode(licenseTag)).enqueue(new Callback<ReturnCarCommentBean>() {
            @Override
            public void onResponse(Call<ReturnCarCommentBean> call, Response<ReturnCarCommentBean> response) {
                if (response.isSuccessful() && response.body() != null && response.body().getMsg_code() == 200) {
                    dismissLoadingDialog();
                    commentTvLicensetag.setText(licenseTag);
                    getCarCommentBean = response.body();
                    tvSure.setVisibility(View.VISIBLE);
                    commentTvTip.setVisibility(View.VISIBLE);
                    if (!TextUtils.isEmpty(response.body().getAttachment().getComment().getImgs())) {
                        List<String> data = Arrays.asList(response.body().getAttachment().getComment().getImgs().replace(",,", ",").split(","));
                        gridViewAdpter = new GridViewAdpter(data, mContext);
                        commentGv0.setAdapter(gridViewAdpter);
                        commentGv0.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                Intent intent = new Intent(mContext, PhotoViewActivity.class);
                                intent.putStringArrayListExtra("pictures", new ArrayList<>(Arrays.asList(response.body().getAttachment().getComment().getImgs().replace(",,", ",").split(","))));
                                intent.putExtra("toIndex", position);
                                int location[] = new int[2];
                                view.getLocationOnScreen(location);
                                intent.putExtra("left", location[0]);
                                intent.putExtra("top", location[1]);
                                intent.putExtra("height", view.getHeight());
                                intent.putExtra("width", view.getWidth());
                                mContext.startActivity(intent);
                            }
                        });
                        maxImages = 6 - data.size();
                        gridViewAddImgesAdpter.setMaxImages(maxImages);
                        if (maxImages <= 0) {
                            commentTvTip.setText("当前照片已满，无法补充备注照片");
                            commentTvTip.setTextColor(Color.parseColor("#999999"));
                            commentGv1.setVisibility(View.GONE);
                            tvSure.setText("完成");
                        } else {
                            commentGv1.setVisibility(View.VISIBLE);
                        }
                    } else {
                        maxImages = 6;
                        commentGv0.setVisibility(View.GONE);
                        commentGv1.setVisibility(View.VISIBLE);
                    }

                } else {
                    dismissLoadingDialog();
                    ToastUtils.makeText(mContext, "车辆查询失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ReturnCarCommentBean> call, Throwable t) {
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void initData() {
        //cache  缓存删除了
        SPUtils.getInstance(mContext).removeValue(SPKey.RETURN_CAR_PIC_NAME);
        fileDir = new File(SDCardUtils.getSDCardPrivateCacheDir(mContext) + File.separator + "returncar");
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        File[] files = fileDir.listFiles();
        if (files != null) {
            Arrays.sort(files);
            for (int i = 0; i < files.length; i++) {
                if (files[i].getName().endsWith("jpg")) {
                    files[i].delete();
                }
            }
        }
        datas = new ArrayList<>();
        gridViewAddImgesAdpter = new GridViewAddImgesAdpter(datas, mContext);
        commentGv1.setAdapter(gridViewAddImgesAdpter);
        commentGv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (datas == null || datas.size() == position) {
                    checkperssionAndCamera();
                } else {
                    Logger.d("returnCarrename4", "click--" + position);
                    Intent intent = new Intent(mContext, PhotoViewActivity.class);
                    intent.putStringArrayListExtra("pictures", datas);
                    intent.putExtra("pictureType", 1);
                    intent.putExtra("toIndex", position);
                    int location[] = new int[2];
                    view.getLocationOnScreen(location);
                    intent.putExtra("left", location[0]);
                    intent.putExtra("top", location[1]);
                    intent.putExtra("height", view.getHeight());
                    intent.putExtra("width", view.getWidth());
                    mContext.startActivity(intent);
                    //((CarTaskActivity) mContext).overridePendingTransition(0, 0);
                }
            }
        });
    }

    public void checkperssionAndCamera() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            List<String> permissionLists = new ArrayList<>();
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                permissionLists.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                permissionLists.add(Manifest.permission.CAMERA);
            }
            if (!permissionLists.isEmpty()) {//有拒绝的权限
                ActivityCompat.requestPermissions(this, permissionLists.toArray(new String[permissionLists.size()]), Constants.PERMISSION_REQUEST_CAMERA);
            } else {
                takePhotoCustom();
            }
        } else {
            takePhotoCustom();
        }
    }

    private void takePhotoCustom() {
        Intent intent = new Intent(mContext, ReturnCarCameraActivity.class);
        intent.putExtra("orderId", orderId);
        intent.putExtra("maxImages", maxImages);
        intent.putExtra("intentFrom", 1);
        startActivity(intent);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        datas = new ArrayList<>();
        File[] files = fileDir.listFiles();
        if (files != null) {
            Arrays.sort(files);
            for (int i = 0; i < files.length; i++) {
                if (files[i].getName().endsWith("jpg") && files[i].getName().startsWith(orderId)) {
                    Logger.d("returnCarrename3OnNewIntent", files[i].getAbsolutePath());
                    datas.add(files[i].getAbsolutePath());
                }
            }
        }
        gridViewAddImgesAdpter.notifyDataSetChanged(datas);
    }

    @OnClick({R.id.title_back, R.id.tv_cancel, R.id.tv_sure})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                AppManager.getAppManager().finishActivity();
                break;
            case R.id.tv_cancel:
                edtSearch.setText("");
                linearCancel.setVisibility(View.GONE);
                break;
            case R.id.tv_sure:
                if (tvSure.getText().toString().equals("完成")) {
                    AppManager.getAppManager().finishActivity();
                } else {
                    checkCommitComment();
                }
                break;
        }
    }

    private void checkCommitComment() {
        showLoadingDialog();
        List<String> success = new ArrayList<>();
        if (SPUtils.getInstance(mContext).getStringValue(SPKey.RETURN_CAR_PIC_NAME) != null) {
            success = Arrays.asList(SPUtils.getInstance(mContext).getStringValue(SPKey.RETURN_CAR_PIC_NAME).split(","));
        }
        File[] files = fileDir.listFiles();
        List<File> unUpdatePics = new ArrayList<>();
        if (files != null) {
            Arrays.sort(files);
            imgs = "";
            for (int i = 0; i < files.length; i++) {
                if (files[i].getName().endsWith("jpg") && !success.contains(files[i].getName())) {
                    unUpdatePics.add(files[i]);
                }
            }
        }

        if (unUpdatePics.size() != 0) {
            Observable
                    .fromIterable(unUpdatePics)
                    .flatMap(new Function<File, ObservableSource<UploadImageBaidu>>() {
                        @Override
                        public ObservableSource<UploadImageBaidu> apply(File file) throws Exception {
                            return Observable.create(new ObservableOnSubscribe<UploadImageBaidu>() {
                                @Override
                                public void subscribe(ObservableEmitter<UploadImageBaidu> emitter) throws Exception {
                                    new ApiStore().getRetrofit(UrlConstant.Request.BASE_URL_NEW, "", "").create(ApiService.class).uploadImageBaidu(((MyApplication) getApplication()).getRequestFieldMap(), "stsToken", "upload").enqueue(new Callback<UploadImageBaidu>() {
                                        @Override
                                        public void onResponse(Call<UploadImageBaidu> call, Response<UploadImageBaidu> response) {
                                            Logger.d("returnCar", "预备上传" + response.body().getAttachment().getBucketName());
                                            response.body().setFile(file);
                                            emitter.onNext(response.body());
                                            emitter.onComplete();
                                        }

                                        @Override
                                        public void onFailure(Call<UploadImageBaidu> call, Throwable t) {
                                            emitter.onComplete();
                                        }
                                    });
                                }
                            });
                        }
                    })
                    .flatMap(new Function<UploadImageBaidu, ObservableSource<File>>() {
                        @Override
                        public ObservableSource<File> apply(UploadImageBaidu uploadImageBaidu) throws Exception {

                            return Observable.create(new ObservableOnSubscribe<File>() {
                                @Override
                                public void subscribe(ObservableEmitter<File> emitter) throws Exception {
                                    Logger.d("returnCar", "上传 开始" + uploadImageBaidu.getFile() + "   " + uploadImageBaidu.getAttachment().getBucketName());
                                    key = getFileNameNoExOrder(uploadImageBaidu.getFile());
                                    UploadPicUtil.getInstance().uploadPicToBos(
                                            uploadImageBaidu.getFile(),
                                            uploadImageBaidu.getAttachment().getAk(),
                                            uploadImageBaidu.getAttachment().getSk(),
                                            uploadImageBaidu.getAttachment().getBucketName(),
                                            uploadImageBaidu.getAttachment().getStsToken(),
                                            uploadImageBaidu.getAttachment().getBucketName(),
                                            key,
                                            new UploadPicUtil.OnFinishListener() {
                                                @Override
                                                public void onSuccess() {
                                                    SPUtils.getInstance(mContext).putStringValue(SPKey.RETURN_CAR_PIC_NAME, SPUtils.getInstance(mContext).getStringValue(SPKey.RETURN_CAR_PIC_NAME) + "," + uploadImageBaidu.getFile().getName());
                                                    emitter.onNext(uploadImageBaidu.getFile());
                                                    emitter.onComplete();
                                                    Logger.d("returnCar", "上传成功" + uploadImageBaidu.getFile().getName());
                                                }

                                                @Override
                                                public void onFailure(String failReason) {
                                                    emitter.onComplete();
                                                    Logger.d("returnCar", "上传失败" + uploadImageBaidu.getFile().getName());
                                                }
                                            });
                                }
                            });
                        }
                    }).subscribe(new Observer<File>() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(File file) {

                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onComplete() {
                    for (int i = 0; i < files.length; i++) {
                        if (files[i].getName().endsWith("jpg") && files[i].getName().startsWith(orderId)) {
                            String name = getFileNameNoExOrder(files[i]);
                            imgs = imgs + name + ",";
                        }
                    }
                    commitComment();
                }
            });
        } else {
            for (File file : files) {
                if (file.getName().endsWith("jpg") && file.getName().startsWith(orderId)) {
                    String name = getFileNameNoExOrder(file);
                    imgs = imgs + name + ",";
                }
            }
            commitComment();
        }
    }

    public void commitComment() {
        JSONObject bodyJson = new JSONObject();
        try {
            bodyJson = new JSONObject(new Gson().toJson(((MyApplication) getApplication()).getRequestFieldMap()));
            bodyJson.put("car_id", getCarCommentBean.getAttachment().getCar_id());
            bodyJson.put("staff_id", getCarCommentBean.getAttachment().getStaff_id());
            JSONObject commentJson = new JSONObject();
            commentJson.put("onGround", getCarCommentBean.getAttachment().getComment().getOnGround());
            if (!TextUtils.isEmpty(getCarCommentBean.getAttachment().getComment().getImgs())) {
                if (getCarCommentBean.getAttachment().getComment().getImgs().endsWith(",")) {
                    commentJson.put("imgs", getCarCommentBean.getAttachment().getComment().getImgs() + imgs);
                } else {
                    commentJson.put("imgs", getCarCommentBean.getAttachment().getComment().getImgs() + "," + imgs);
                }
                if (!TextUtils.isEmpty(getCarCommentBean.getAttachment().getComment().getArrIndex())) {
                    commentJson.put("arrIndex", getCarCommentBean.getAttachment().getComment().getArrIndex() + "," + getCarCommentBean.getAttachment().getComment().getImgs().replace(",,", ",").split(",").length);
                } else {
                    commentJson.put("arrIndex", getCarCommentBean.getAttachment().getComment().getImgs().replace(",,", ",").split(",").length);
                }
                if (!TextUtils.isEmpty(getCarCommentBean.getAttachment().getComment().getUidList())) {
                    commentJson.put("uidList", getCarCommentBean.getAttachment().getComment().getUidList() + "," + MyApplication.getInstance().getUserId() + "");
                } else {
                    commentJson.put("uidList", MyApplication.getInstance().getUserId() + "");
                }
            } else {
                commentJson.put("imgs", imgs);
                commentJson.put("arrIndex", "0");
                commentJson.put("uidList", MyApplication.getInstance().getUserId() + "");
            }
            commentJson.put("remarkMsg", getCarCommentBean.getAttachment().getComment().getRemarkMsg());
            commentJson.put("orderId", getCarCommentBean.getAttachment().getComment().getOrderId());
            bodyJson.put("comment", commentJson);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Logger.d("returnCar", bodyJson.toString());
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), bodyJson.toString());
        new ApiStore().getRetrofit(UrlConstant.Request.BASE_URL_NEW, "", "").create(ApiService.class).returnCarComment(body).enqueue(new Callback<ReturnCarCommentBean>() {
            @Override
            public void onResponse(Call<ReturnCarCommentBean> call, Response<ReturnCarCommentBean> response) {
                if (response.isSuccessful() && response.body() != null && response.body().getMsg_code() == 200) {
                    dismissLoadingDialog();
                    AppManager.getAppManager().finishActivity();
                } else {
                    dismissLoadingDialog();
                    ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ReturnCarCommentBean> call, Throwable t) {
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
            }
        });
    }

    /*
   * Java文件操作 获取不带扩展名的文件名
   */
    public String getFileNameNoExOrder(File nameFile) {
        String filename = nameFile.getName();
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length()))) {
                int index = filename.lastIndexOf("-");
                return filename.substring(index + 1, dot);
            }
        }
        return filename;
    }
}
